package net.mikoo.seals.boss.biz.services.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import net.mikoo.seals.boss.biz.manager.CompanyManager;
import net.mikoo.seals.boss.biz.mapper.client.CompanyMapper;
import net.mikoo.seals.boss.biz.mapper.client.MemberMapper;
import net.mikoo.seals.boss.biz.mapper.client.StaffMapper;
import net.mikoo.seals.boss.biz.services.CompanyServices;
import net.mikoo.seals.boss.common.BaseServices;
import net.mikoo.seals.boss.common.PageModel;
import net.mikoo.seals.boss.common.WebContext;
import net.mikoo.seals.boss.common.enums.CompanyStatusEnum;
import net.mikoo.seals.boss.common.enums.MobileStatusEnum;
import net.mikoo.seals.boss.common.enums.PartyStatusEnum;
import net.mikoo.seals.boss.common.enums.StaffStatusEnum;
import net.mikoo.seals.boss.common.exception.ParametersException;
import net.mikoo.seals.boss.common.utils.IPUtil;
import net.mikoo.seals.boss.common.utils.MD5Util;
import net.mikoo.seals.boss.model.Company;
import net.mikoo.seals.boss.model.CompanyQuery;
import net.mikoo.seals.boss.model.Party;
import net.mikoo.seals.boss.model.Person;
import net.mikoo.seals.boss.model.Staff;
import net.mikoo.seals.boss.model.UserLogin;

@Service
public class CompanyServicesImpl extends BaseServices implements CompanyServices {
	
	Logger logger = LoggerFactory.getLogger(CompanyServicesImpl.class);

	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private CompanyManager companyManager;
	
	@Autowired
	private  StaffMapper staffMapper;
	
	@Autowired
	private  MemberMapper memberMapper;
	
	@Override
	public void save(Company company) {
		
		companyManager.checkCreateParms(company);
		
		company.setCompanyStatus(CompanyStatusEnum.CREATED.code());
		company.setCreateTime(new Date());
			
			clientTransactionTemplate.execute(new TransactionCallbackWithoutResult() {

				@Override
				protected void doInTransactionWithoutResult(TransactionStatus status) {
					try {


						companyMapper.insert(company);
						
						String userLoginId =  company.getUserLoginId();
						String password =  company.getPassword();
						
						
						//判断注册管理员用户是否已经存在 如果不存在重新创建、已存在关联公司
						UserLogin userLogin = memberMapper.selectByUserLoginId(userLoginId);
						if(userLogin != null) {
							Staff staff = new Staff();
							staff.setStaffType("LEGAL_PERSON");
							staff.setPartyId(userLogin.getPartyId());
							staff.setCompanyId(company.getCompanyId());
							staff.setName(company.getLegalPerson());
							staff.setMobile(userLogin.getPerson().getMobile());
							staff.setIsSystem("N");
							staff.setCreateTime(new Date());
							staff.setStaffStatus(StaffStatusEnum.NORMAL.code());
							staffMapper.insert(staff);
						
						}else {

							// 创建party
							Party party = new Party();
							party.setUserLoginId(userLoginId);
							party.setCreatedTime(new Date());
							party.setIsSystem("N");
							party.setPartyStatus(PartyStatusEnum.NORMAL.code());
							memberMapper.insertBackPrimaryKey(party);

							// 创建登录帐户
							userLogin = new UserLogin();
							userLogin.setUserLoginId(userLoginId);
							userLogin.setCurrentPassword(MD5Util.Md5(password));
							userLogin.setPartyId(party.getPartyId());
							userLogin.setRegisterTime(new Date());
							userLogin.setRegisterIp(IPUtil.getRemoteAddr(WebContext.getRequest()));
							userLogin.setIsSystem("N");
							memberMapper.insertUserLogin(userLogin);

							// 创建人员信息
							Person person = new Person();
							person.setName(company.getLegalPerson());
							person.setMobile(userLoginId);
							person.setUserLoginId(userLogin.getUserLoginId());
							person.setPartyId(party.getPartyId());
							person.setMobileStatus(MobileStatusEnum.NOT_CERTIFIED.code());
							memberMapper.insertPerson(person);
							
							//创建管理员和公司关联信息
							Staff staff = new Staff();
							staff.setCompanyId(company.getCompanyId());
							staff.setStaffType("LEGAL_PERSON");
							staff.setPartyId(userLogin.getPartyId());
							staff.setName(company.getLegalPerson());
							staff.setMobile(userLoginId);
							staff.setIsSystem("N");
							staff.setCreateTime(new Date());
							staff.setStaffStatus(StaffStatusEnum.NORMAL.code());
							staffMapper.insert(staff);
							
							
							
						}
						

					} catch (ParametersException e) {
						logger.error("", e);
						status.setRollbackOnly();
						throw e;
					} catch (Exception e) {
						logger.error("", e);
						status.setRollbackOnly();
						throw e;
					}

				}

			});
		
	}

	@Override
	public void modifyByPrimaryKey(Company company) {
		
		if(company == null){
			throw new ParametersException("company is null!");
		}
		companyMapper.delete(company);
	}
	
	@Override
	public Company loadByPrimaryKey(Long companyId) {
		
		if(companyId == null){
			throw new ParametersException("companyId is null!");
		}
		
		Company company = companyMapper.selectInfoById(companyId);
		return company;
	}
	
	
	@Override
	public void deleteByPrimaryKey(Long companyId) {
		
				
	}
	
	@Override
	public PageModel<Company> loadByQueryToPage(CompanyQuery query) {
		
		
		List<Company> datas = companyMapper.selectByQueryToPage(query);
		Integer total = companyMapper.countByQueryToPage(query);
		PageModel<Company> pm = new PageModel<Company>(total,datas);
		return pm;
	}

	@Override
	public List<Company> getListByQuery(CompanyQuery query) {
		
		List<Company> companys  = companyMapper.selectListByQuery(query);
		
		return companys;
		
	}

	
}
